package com.geek.service;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.geek.domain.Order;
import com.geek.mapper.OrderMapper;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrderService {

    Snowflake snowflake = IdUtil.createSnowflake(1, 1);


    @Autowired
    private OrderMapper orderMapper;

    @Transactional
    @ShardingTransactionType(value = TransactionType.XA)
    public void add() {
        List list = new ArrayList();

        Order order1 = new Order();
        order1.setOrderId(snowflake.nextId());
        order1.setUserId(Long.valueOf(1));
        order1.setUsername("张三");
        list.add(order1);

        Order order2 = new Order();
        order2.setOrderId(snowflake.nextId());
        order2.setUserId(Long.valueOf(2));
        order2.setUsername("李四");
        list.add(order2);

        orderMapper.add(list);
        // 模拟异常，事务是否是原子性
        throw new RuntimeException();
    }

    public List<Order> get() {
        return orderMapper.get();
    }

    public void edit(Order order) {
        orderMapper.edit(order);
    }

    public void delete(Long orderId) {
        orderMapper.delete(orderId);
    }
}
